package com.spontaneappnew.services;

import java.util.List;

import com.google.android.gms.location.Geofence;
import com.google.android.gms.location.LocationClient;
import com.spontaneappnew.R;
import com.spontaneappnew.activities.SplashScreenActivity;

import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

public class GeofenceIntentService extends IntentService {
	
	public static final String TRANSITION_INTENT_SERVICE = "ReceiveTransitionsIntentService";

	public GeofenceIntentService() {
		super(TRANSITION_INTENT_SERVICE);
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		if (LocationClient.hasError(intent)) {
			// Get the error code with a static method
            int errorCode = LocationClient.getErrorCode(intent);
            // Log the error
            Log.e("GeofenceIntentService",
                    "Location Services error: " +
                    Integer.toString(errorCode));
        } else {
            int transitionType = LocationClient.getGeofenceTransition(intent);
            List<Geofence> triggerList = LocationClient.getTriggeringGeofences(intent);
            if (transitionType == Geofence.GEOFENCE_TRANSITION_ENTER) {
                for (Geofence geofence : triggerList) {
                	generateEntranceNotification(geofence.getRequestId());
                }
            } else if(transitionType == Geofence.GEOFENCE_TRANSITION_EXIT){
            	for (Geofence geofence : triggerList) {
                    generateExitNotification(geofence.getRequestId());
                }
            // An invalid transition was reported
            } else {
            	Log.e("GeofenceIntentService", "Geofence transition error: " +
                        Integer.toString(transitionType));
            }
        }
	}
	
	private void generateEntranceNotification(String requestId) {
        long currTime = System.currentTimeMillis();
        int indexOfAtAt = requestId.indexOf("@@") + 2;
        String placeName =  requestId.substring(indexOfAtAt);
        String msgTitle = "You have Arrived to " + placeName + "!";
        String msgText = "Thanks for using SpontaneApp! enjoy :)";
        NotificationCompat.Builder builder =
                new NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.ic_app_icon)
                        .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.app_notification))
                        .setContentTitle(msgTitle)
                        .setContentText(msgText)
                        .setTicker(msgTitle)
                        .setAutoCancel(true)
                        .setDefaults(Notification.DEFAULT_SOUND)
                        .setWhen(currTime);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify((int) currTime, builder.build());
    }
	
	private void generateExitNotification(String requestId) {
        long currTime = System.currentTimeMillis();
        // the @@ is used as a delimiter to separate the place's ID from Parse to the place's name so we can send
        // it as arguments in the intent
        int indexOfAtAt = requestId.indexOf("@@");
        String placeId = requestId.substring(0, indexOfAtAt);
        String placeName =  requestId.substring(indexOfAtAt+2);
        String msgTitle = "Thanks for visiting " + placeName + "!";
        String msgText = "We hope you enjoyed yourself.. Please rate the place and share your experience" +
        		" with us. You can do so by clicking this";
        // the intent starts the splash activity which is the launcher activity and passes a flag to let it know if it should start the 
        // RateAndComment activity, we do that in order to clean the stack properly so the only activity in the stack will be the rate activity
        Intent notifyIntent = new Intent(this, SplashScreenActivity.class);
        notifyIntent.putExtra("startRateActivity", true);
        notifyIntent.putExtra("placeId", placeId);
        notifyIntent.putExtra("placeName", placeName);
        notifyIntent.setFlags(Intent. FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);

        PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, notifyIntent, 
        		PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder builder =
                new NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.ic_app_icon)
                        .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.app_notification))
                        .setContentTitle(msgTitle)
                        .setContentText(msgText)
                        .setTicker(msgTitle)
                        .setContentIntent(pendingIntent)
                        .setAutoCancel(true)
                        .setDefaults(Notification.DEFAULT_SOUND)
                        .setWhen(currTime);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify((int) currTime, builder.build());
    }

}
